package main

import (
	"encoding/binary"
	"fmt"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"
)

var (
	frames = make(map[*TcpClientEx]uint16)
	lock   sync.RWMutex
)

func main() {
	server := NewTcpServer()

	server.OnNewConnect = func(client *TcpClientEx) {
		lock.Lock()
		frames[client] = 0
		lock.Unlock()
	}
	server.OnDisconnect = func(client *TcpClientEx) {
		lock.Lock()
		delete(frames, client)
		lock.Unlock()
	}
	server.OnMsgReceive = func(client *TcpClientEx, bmsg []byte) {
		size := binary.LittleEndian.Uint16(bmsg[0:2])
		lock.Lock()
		if _, ok := frames[client]; ok {
			frames[client] = size
		}
		lock.Unlock()
		client.Send(bmsg)
	}
	server.Listen(26720)

	go func() {
		for {
			time.Sleep(time.Second)
			fmt.Print("活跃连接数：", len(frames), "\t")
			var minfps uint16 = 0
			lock.RLock()
			for _, fps := range frames {
				if minfps == 0 {
					minfps = fps
				}
				if fps < minfps {
					minfps = fps
				}
			}
			lock.RUnlock()
			fmt.Println("最小帧率：", minfps)
		}
	}()

	WaitExit()
}

func WaitExit() {
	c := make(chan os.Signal)
	signal.Notify(c, syscall.SIGINT, syscall.SIGHUP)

	sig := <-c
	fmt.Println("out sig:", sig)
}
